<?php
namespace app\api\controller;
use app\api\model\Order as OrderModel;
use app\api\model\Wxapp as WxappModel;
use app\api\model\Cart as CartModel;
use app\common\library\wechat\WxPay;
use app\api\model\User as UserModel;
use app\api\model\Goods as GoodsModel;
use app\api\model\Setting as SettingModel;
use app\api\model\Printer as PrinterModel;
use app\api\model\Flavor as FlavorModel;
use think\Cache;

/**
 * 订单控制器
 */
class Order extends Controller
{
    private $user;

    /**
     * 构造方法
     */
    public function _initialize()
    {
        parent::_initialize();
        $this->user = $this->getUser();   // 用户信息
    }

    /**
     * 订单确认-购物车结算
	 * $food_mode 点餐模式 1店内，2打包，3外卖，大于10000店内扫码
	 * $pay_mode 支付模式 0微信，1余额
	 * 店内就餐参数 $people=就餐人数,$ware_price=餐具调料费,$order_pay_price=0
	 * $message=买家留言
	 * $flavor=口味选择
	 * $arrive_time = 到店时间
     */
    public function cart($food_mode,$pay_mode=0,$people=0,$ware_price=0,$location='',$message='',$flavor='',$arrive_time='')
    {	
		$model =  new FlavorModel;
		$flavor_list = $model->getList();
        // 商品结算信息
        $model = new OrderModel;
        $order = $model->getCart($this->user,$food_mode,$this->shop_id,$location);
		$order['flavor_list'] = $flavor_list;
        if (!$this->request->isPost()) {
            return $this->renderSuccess($order);
        }
		if($food_mode==2){
			$time = explode(':',$arrive_time);
			$order['arrive_time'] = mktime(0,0,0,date('m'),date('d'),date('Y'))+$time[0]*3600+$time[1]*60;
		}
        // 创建订单
        if (!$model->add($this->user['user_id'], $order,$this->shop_id,$food_mode,$people,$ware_price,$message,$flavor)) {
			$error = $model->getError() ?: '订单创建失败';
			return $this->renderError($error);  
        }
		// 清空购物车
		$Card = new CartModel($this->user['user_id'],$this->shop_id);
		$Card->clearAll();
		// 发起微信支付
        if($pay_mode==0){
            return $this->renderSuccess([
                'payment' => $this->wxPay($model['order_no'], $this->user['open_id']
                    , $order['order_pay_price']),
                'order_id' => $model['order_id']
            ]);
		}
		//发起余额支付
		$order = OrderModel::detail($model['order_id']);
		$user = UserModel::detail($this->user['user_id']);
		if($user['wallet']<$order['pay_price']){
			return [
				'code' => -10, 
				'msg' => '余额不足', 
				'data' => []
			];
		}
		$user->wallet = ['dec',$order['pay_price']];//扣除余额
		$user->pay = ['inc', $order['pay_price']];//增加消费金额
		//$user->score = ['inc', $order['pay_price']*100];//增加积分
		$user->save();
		//订单排序号
		;
		if($row_no = Cache::get('order_row_no_'.$order['wxapp_id'].'_'.$this->shop_id)){
			if($row_no<100){
				$row_no = $row_no+1;
			}else{
				$row_no=1;
			}	
		}else{
			$row_no = 1;
		}
		Cache::set('order_row_no_'.$order['wxapp_id'].'_'.$this->shop_id, $row_no);		
		// 更新商品库存、销量
		$Goods = new GoodsModel;
		$Goods->updateStockSales($order['goods']);
		// 更新订单状态
		$order->row_no = $row_no;
		$order->pay_status = 20;
		$order->pay_time = time();
		
		//发送模板消息 - 使用公众号
		$msg = make_new_order_msg($order);
		f_tpl_msg($msg,8,$order['wxapp_id'],$this->shop_id);
		
		//获取打印机配置
		if($p_set = SettingModel::getItem('printer')){
			//如果开启打印机并且开启支付后打印 - 则执行打印小票
			if($p_set['is_open']==1 AND $p_set['pay_p']==1){
				$p = new PrinterModel;
				$p->gotoPrint($order,$p_set['p_n']);
			}
		}
		dealer($order['order_id']); //分销-分账
		//如果是外卖
		if($order['table_id']==3){
			
		}
		$order->save();
		return $this->renderSuccess(['order_id' => $order['order_id']]);
        
    }

    /**
     * 构建微信支付
     */
    private function wxPay($order_no, $open_id, $pay_price)
    {
        $wxConfig = WxappModel::getWxappCache();
        $WxPay = new WxPay($wxConfig);
        return $WxPay->unifiedorder($order_no, $open_id, $pay_price);
    }

}
